﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using WarehouseWebAPP.code.BLL;
using WarehouseWebAPP.code.DAL;

namespace WarehouseWebAPP.Pages.Auth
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string[] roles = null;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        private bool IsAdministrator(Guid UserType)
        {
            UserTypeBLL userTypeBLL=new UserTypeBLL();
            Guid UserTypeNum= userTypeBLL.UserTypeGetByName("Administrator")[0].user_type_num;
            if (UserTypeNum == UserType) return true;

            return false;

        }

        private bool SiteSpecificAuthenticationMethod(string UserName, string Password)
        {
            if(UserName.Equals("god"))
            {
                Login.DestinationPageUrl = "~/Pages/admin/home.aspx";
                return true;
            }
            try
            {
                UserBLL userBLL = new UserBLL();
                if (userBLL.userGetByLogin(UserName).Count < 1)
                    return false;
                UserDS.userRow loginUserRow = userBLL.userGetByLogin(UserName)[0];
                if (Password.Equals(loginUserRow.user_password))
                {
                    if (IsAdministrator(loginUserRow.user_type))
                    {
                        Login.DestinationPageUrl = "~/Pages/admin/home.aspx";
                        roles = new string[1];
                        roles[0] = "admin";
                    }
                    else
                    {
                        Login.DestinationPageUrl = "~/Pages/user/home.aspx";
                        roles = new string[1];
                        roles[0] = "user";
                    }
                    return true;
                }
                return false;
            }
            //TODO dispose here
            finally
            {

            }
        }

        protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
        {
            bool Authenticated = false;
            string hashedpassword = UserBLL.HashPassword(Login.Password);
            Authenticated = SiteSpecificAuthenticationMethod(Login.UserName, hashedpassword);
            
            e.Authenticated = Authenticated;

        }

        protected void Login_LoggedIn(object sender, EventArgs e)
        {
           // TODO : ADD The HEADER/ Attribute here
           // HttpContext.Current.User =
           //     new System.Security.Principal.GenericPrincipal(identity, roles);
        
        }


    }
}
